<template>
	<Menu 
		ref="sider-ul"
		theme="dark" 
		:open-names="openedNames"
		:active-name="activeName"
		accordion 
		width="200" 
		@on-select="changeMenu"
		@on-open-change="openMenu"
		class="sider-ul">
		<!--{{openedNames }}{{activeName}}-->
        <Submenu :name="level1.name" v-for="level1 in routeList" v-if="level1.hidden" :key="level1.name">
            <template slot="title">
            	<div class="menu-item-wrapper">
	                <div :class="handleClass(level1)" class="menu-icon"></div>
	                <span>{{level1.title}}</span>
                </div>
            </template>
            <template v-for="level2 in level1.children">
            	<template v-if="level2.children && level2.hidden">
            		<MenuGroup :title="level2.title" :key="level2.name">
                        <MenuItem 
                        	v-if="level3.hidden"
                        	:name="level3.name" 
                        	v-for="level3 in level2.children" 
                        	:key="level3.name">
                        	{{level3.title}}
                        </MenuItem>
                    </MenuGroup>
            	</template>
            	<template v-else>
            		<MenuItem 
            			v-if="level2.hidden"
            			:name="level2.name" 
            			:key="level2.name" >
            			{{level2.title}}
            		</MenuItem>
            	</template>
            </template>
        </Submenu>
    </Menu>
	<!--<ul class="sider-ul" :class="projectName === 'qax' ? 'qax-sider-ul' : ''" :style="{'height':height}">
		<template v-for="level1 in routeList">
			<li class="menu-items" :id="'menu-'+level1.name" :key="level1.name" v-if="level1.hidden">
				<div @click.stop="changeMenuItem(level1)" class="menu-item-wrap" :class="{menuItemActive:showMark(level1)}">
					<div class="item-icon" :class="handleClass(level1)"></div>
					<div class="item-text">{{level1.title}}</div>
					<div class="long-line-active" v-if="projectName !== 'qax'"></div>
					<div class="item-arrow" v-if="projectName === 'qax' && hasChildren(level1)">
						<Icon type="ios-arrow-down" v-show="!showMark(level1)"/>
						<Icon type="ios-arrow-up" v-show="showMark(level1)"/>
					</div>
				</div>
				<div class="submenu-wrap" :class="{showSubMenu:showMark(level1)}" v-if="hasChildren(level1)">
					<template v-for="level2 in level1.children">
						<div class="submenu-item" :key="level2.name" :id="'menu-'+ level2.name" :class="{colorOrange:showMark(level2)}" v-if="level2.hidden && !hasChildren(level2)" @click.stop="changeMenuItem(level2,level1)">
							<div class="short-active-line"></div>
							{{level2.title}}
						</div>
						<div class="submenu-item" :key="level2.name" v-if="level2.hidden && hasChildren(level2)">
							<div>
								<div class="ring-style"></div>
								{{level2.title}}
							</div>
							<template v-for="level3 in level2.children">
								<div :id="'menu-'+level3.name" v-if="level3.hidden" :key="level3.name">
									<div style="margin-left: 20px;line-height: 2.3" :class="{colorOrange:showMark(level3)}" @click.stop="changeMenuItem(level3,level1)">
										<div class="short-active-line"></div>
										{{level3.title}}
									</div>
								</div>
							</template>
						</div>
					</template>
				</div>
			</li>
		</template>
	</ul>-->
</template>
<script>
	import {mapState} from 'vuex'
	export default {
		name: 'SideMenu',
		mixins: [],
		components: {

		},
		props: {
			activeNames: {
				type: Array,
				default: () => []
			},
			routeList: {
				type: Array,
				default: () => []
			},
			height: ''
		},
		data() {
			return {
				activeMenuList: [],
				menuListAll:[],
				menuListAllHidden:[],
				menuListAllShow:[],
				openedNames:[],
				activeName:''
			}
		},
		methods: {
			showMark(menu) {
				return this.activeMenuList.includes(menu.name);
			},
			hasChildren(menu){
				return menu.children && menu.children.filter(menu => menu.hidden).length > 0;
			},
			//			markRoute(activeList, routeList) {
			//				routeList.forEach(route => {
			//					if(activeList.includes(route.name) && route.hidden) {
			//						route.meta.mark = true
			//					} else {
			//						if(route.meta) {
			//							route.meta.mark = false
			//						}
			//					}
			//					if(route.children) {
			//						this.markRoute(activeList, route.children)
			//					}
			//				})
			//			},
			flatDeep(arr, d = 1, result = []) {
				if(d > 0) {
					for(let item of arr) {
						if(Array.isArray(item.children)) {
							result.push(item)
							this.flatDeep(item.children, Infinity, result)
						} else {
							result.push(item)
						}
					}
					return result
				} else {
					return arr.slice();
				}
			},
			routeHasHidden(name) {
				return this.menuListAllHidden.find(menu => menu.name == name);
			},
			//根据子菜单获取一级菜单
			getLevel1Menu(name) {
				let menu = this.menuListAll.find(route => route.name == name);
				if(menu && menu.parentRoute) {
					return this.getLevel1Menu(menu.parentRoute.name);
				} else {
					return menu;
				}
			},
			gotoOtherShowRoute(name) {
				//获取当前菜单信息
				let menuInfo = this.menuListAll.find(route => route.name == name);
				if(menuInfo && menuInfo.parentRoute) { //如果当前菜单是子菜单（二级/三级）
					//获取一级父菜单信息
					let level1Menu = this.getLevel1Menu(menuInfo.name);
					//获取父级菜单
					let pmenu = menuInfo.parentRoute;
					if(level1Menu.hidden) { //如果一级菜单显示
						if(menuInfo.level == 2) { //二级
							//获取对当前菜单的同级菜单
							let siblingsMenu = menuInfo.parentRoute.children;//this.menuListAll.filter(menu => menu.pid == menuInfo.pid);
							let siblingsShowMenu = siblingsMenu.find(menu => menu.hidden && menu.hidden != undefined);
							if(siblingsShowMenu) { //如果兄弟菜单中有显示的菜单
								let firstShowRoute = siblingsShowMenu;
								this.changeMenuItem(firstShowRoute, level1Menu);
							} else {
								this.gotoOtherShowRoute(level1Menu.name);
							}
						} else { //三级
							if(pmenu.hidden) {//二级菜单显示
								let siblingsMenu = menuInfo.parentRoute.children;//this.menuListAll.filter(menu => menu.pid == menuInfo.pid);
								let siblingsShowMenu = siblingsMenu.find(menu => menu.hidden && menu.hidden != undefined);
								if(siblingsShowMenu) { //如果兄弟菜单中有显示的菜单
									let firstShowRoute = siblingsShowMenu;
									this.changeMenuItem(firstShowRoute, level1Menu);
								}
							} else { //二级菜单隐藏
								//获取父级菜单的兄弟菜单
								let siblingsMenu = level1Menu.children;
								let siblingsShowMenu = siblingsMenu.find(menu => menu.hidden && menu.hidden != undefined);
								if(siblingsShowMenu) { //如果兄弟菜单中有显示的菜单
									let firstShowRoute = siblingsShowMenu;
									this.changeMenuItem(firstShowRoute.children ? firstShowRoute.children[0] : firstShowRoute);
								} else {
									this.gotoOtherShowRoute(level1Menu.name);
								}
							}
						}
					} else { //一级菜单隐藏
						this.gotoOtherShowRoute(level1Menu.name);
					}
				} else {
					let firstShowRoute = this.menuListAllShow.length > 0 ? this.menuListAllShow[0] : '';
					if(firstShowRoute) { //有显示的路由
						this.changeMenuItem(firstShowRoute);
					} else {
						this.$Message.warning('没有可用的菜单');
						setTimeout(() => {
							this.$emit('on-select', 'login')
						})
					}
				}
			},
			// 设置icon
			handleClass(value) {
				let {
					defClass,
					activeClass,
					mark
				} = value.meta;
				if(this.projectName == 'qax'){
					return defClass
				}else{
					return this.showMark(value) ? activeClass : defClass
				}
			},
			changeMenu(name){
				let menu = this.menuListAllShow.find(menu => menu.name == name);
				this.changeMenuItem(menu);
			},
			openMenu(menus){
				let menu = this.menuListAllShow.find(menu => menu.name == menus[0]);
				this.changeMenuItem(menu);
			},
			// 切换导航栏
			changeMenuItem(menu, level1Menu) { //当前菜单，一级菜单
				let name = menu.name;
				let level = menu.level;
				let children = menu.children;
				let markMenuObj = sessionStorage.getItem('markMenuObj') ? JSON.parse(sessionStorage.getItem('markMenuObj')) : {};
				if(level == 1) {
					// 切换时是否跳到上次点击的子菜单栏
					let prevMarkName = markMenuObj[name];
					if(prevMarkName) {
						this.$emit('on-select', prevMarkName)
					} else {
						this.$emit('on-select', name)
					}
				} else {
					this.$emit('on-select', name)
				}
			},
			getActiveMenuList(name,list = []){ //根据当前菜单找到所有的父级菜单
				if(!name){
					return list;
				}
				let menu = this.menuListAll.find(route => route.name == name);
				list.unshift(name);
				if(menu && menu.parentRoute) {
					let pMenu = menu.parentRoute;
					return this.getActiveMenuList(pMenu.name,list);
				} else {
					return list;
				}
			},
			initRoute(){ //设置当前mark的菜单列表及菜单显示位置
				let activeMenuList = this.$route.matched.map(item => item.name).filter(item => item !== 'main');
				let storageMenuList = sessionStorage.getItem('activeMenuList');
				storageMenuList = storageMenuList && JSON.parse(storageMenuList) || [];
				let markMenuObj = sessionStorage.getItem('markMenuObj') ? JSON.parse(sessionStorage.getItem('markMenuObj')) : {};
				let activeName = '';
				if(activeMenuList.length > 0) {
					if(activeMenuList[0] == 'parentView') { //非菜单页
						let setActiveMenuist = this.getActiveMenuList(this.$route.meta.activeName);
						if(JSON.stringify(storageMenuList) != JSON.stringify(setActiveMenuist)){ //如果详情页设置的高亮菜单和存储的高亮菜单不一致,说明详情页需要高亮的菜单和当前高亮的菜单不匹配（以详情页为主）
							if(setActiveMenuist.length > 0){
								this.activeMenuList = setActiveMenuist; //重新设置触发菜单
								activeName = this.activeMenuList[this.activeMenuList.length - 1];
								this.$router.push(activeName);
//								sessionStorage.setItem('activeMenuList', JSON.stringify(this.activeMenuList));
//								if(this.activeMenuList.length > 1) {
//									markMenuObj[this.activeMenuList[0]] = activeName;
//									sessionStorage.setItem('markMenuObj', JSON.stringify(markMenuObj));
//								}
							}else{
								if(storageMenuList.length > 0) {
									this.activeMenuList = storageMenuList;
									activeName = this.activeMenuList[this.activeMenuList.length - 1];
								} else {
									let toName = this.routeList.length > 0 ? this.routeList[0].name : 'main'
									this.$emit('on-select', toName);
									return;
								}
							}
						}else{
							if(storageMenuList.length > 0) {
								this.activeMenuList = storageMenuList;
								activeName = this.activeMenuList[this.activeMenuList.length - 1];
							} else {
								let toName = this.routeList.length > 0 ? this.routeList[0].name : 'main'
								this.$emit('on-select', toName);
								return;
							}
						}
					} else { //菜单页
						this.activeMenuList = activeMenuList;
						activeName = this.activeMenuList[this.activeMenuList.length - 1];
						//记录当前菜单
						sessionStorage.setItem('activeMenuList', JSON.stringify(this.activeMenuList))
						if(activeMenuList.length > 1) {
							markMenuObj[this.activeMenuList[0]] = activeName;
							sessionStorage.setItem('markMenuObj', JSON.stringify(markMenuObj));
						}
					}
					this.openedNames = [this.activeMenuList[0]];
					this.activeName = activeName;
				} else {
					if(storageMenuList.length > 0) {
						this.$emit('on-select', storageMenuList[storageMenuList.length - 1])
						return;
					} else {
						let toName = this.routeList.length > 0 ? this.routeList[0].name : 'main'
						this.$emit('on-select', toName)
						return;
					}
				}
				if(this.routeHasHidden(activeName)) {
					this.gotoOtherShowRoute(activeName);
					return;
				}
				//菜单滚动位置
				this.$nextTick(() => {
					let oUl = document.getElementsByClassName("sider-ul")[0];
					let el = document.getElementById('menu-' + this.activeMenuList[0]);
					if(oUl && el) {
						oUl.scrollTop = (el.offsetTop - oUl.offsetTop) - (oUl.offsetHeight - el.offsetHeight) / 2;
					}
				})
			},
			setMenuLevel(routeList,parentRoute,level = 0){
				level++;
				routeList.forEach(route => {
					route.level = level;
					if(parentRoute){
						route.parentRoute = parentRoute;
					}
					if(route.children && route.children.length > 0){
						this.setMenuLevel(route.children,route,level);
					}
				})
			},
		},
		computed: {
			...mapState(['projectName']),
		},
		beforeDestroy() {
			sessionStorage.removeItem('markMenuObj');
			sessionStorage.removeItem('activeMenuList');
		},
		updated() {

		},
		watch: {
			activeNames(val) {
				this.initRoute();
			},
			openedNames(){
				this.$nextTick(() => {
			        this.$refs['sider-ul'].updateOpened();
			        this.$refs['sider-ul'].updateActiveName();
			    })
				
			},
			routeList(val) {
				this.setMenuLevel(val);
				this.menuListAll = this.flatDeep(val, Infinity);
				this.menuListAllHidden = this.menuListAll.filter(menu => !menu.hidden && menu.hidden != undefined); //所有隐藏的菜单，无层级
				this.menuListAllShow = this.menuListAll.filter(menu => menu.hidden); //所有未被隐藏的菜单，无层级
				this.initRoute();
			}
		},
		mounted() {
			if(this.routeList.length > 0){
				this.setMenuLevel(this.routeList);
				this.menuListAll = this.flatDeep(this.routeList, Infinity);
				this.menuListAllHidden = this.menuListAll.filter(menu => !menu.hidden && menu.hidden != undefined); //所有隐藏的菜单，无层级
				this.menuListAllShow = this.menuListAll.filter(menu => menu.hidden); //所有未被隐藏的菜单，无层级
				this.initRoute();
				
			}
			this.$nextTick(() => {
				this.$refs['sider-ul'].updateOpened();
				this.$refs['sider-ul'].updateActiveName();
			})
		}
	}
</script>
<style scoped>
	/*菜单栏样式*/
	
	.sider-ul {
		/* height: calc(100% - 175px - 307px); */
		flex:1 1 auto;
		overflow-y: auto;
		position: static;
		overflow-x: hidden;
		scrollbar-width: none;
	}
	
	.sider-ul::-webkit-scrollbar {
		width: 0;
	}
	.sider-ul.ivu-menu-dark{
		background-color: var(--menu-bgcolor);
	}
	
	/deep/.sider-ul .ivu-menu-submenu,
	/deep/.sider-ul .ivu-menu-opened .ivu-menu-submenu-title{
		background: var(--menu-bgcolor);
	}
	.sider-ul .menu-item-wrapper{
		color:rgba(255,255,255,0.65);
	}
	.ivu-menu-opened .menu-item-wrapper,
	.ivu-menu-child-item-active .menu-item-wrapper{
		color: #fff;
	}
	.sider-ul .menu-item-wrapper,
	.sider-ul .ivu-menu-submenu-title,
	.sider-ul .ivu-menu-opened .ivu-menu-submenu-title{
		display: flex;
    	align-items: center;
	}
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-submenu .ivu-menu-item-active{
		margin:0 10px;
		border-radius: 3px;
	}
	/deep/.sider-ul.ivu-menu-dark.ivu-menu-vertical .ivu-menu-opened .ivu-menu-submenu-title{
		background: #10182d;
	}
	.sider-ul .ivu-menu-item-group-title{
		background: #0d1121;
	}
	/deep/.sider-ul .ivu-menu{
		background: #0d1121;
	}
	.sider-ul .ivu-menu-item{
		/*background: #0d1121;*/
		margin:0 10px;
		padding: 10px 24px;
	}
	.menu-icon{
		height: 20px!important;
		margin-right: 10px;
	}
</style>
<style scoped src="./menu-icon.css">